package com.niit.utils;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.niit.bean.UserInfo;
import com.niit.service.UserInfoService;
import com.niit.service.impl.UserInfoServiceImpl;

@WebServlet("/FileUploadServlet")
public class FileUploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		UserInfo info = new UserInfo();
		try {
			DiskFileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			if(!ServletFileUpload.isMultipartContent(request)){
				return;
			}
			List<FileItem> list = upload.parseRequest(request);
			for(FileItem item:list){
				if(item.isFormField()){
					
					String name = item.getFieldName();
					String value = null;
					if(!"signature".equals(name)){
						value = new String(item.getString().getBytes("ISO-8859-1"),"UTF-8");
					}else{
						value=new String(item.getString().getBytes("ISO-8859-1"),"UTF-8");
					}
					
					System.out.println(name+"="+value);
					BeanUtils.setProperty(info, name, value);
				}else{
					String name = item.getName();
					String fileName = name.substring(name.lastIndexOf("\\")+1);
					InputStream in = item.getInputStream();
					String savepath = this.getServletContext().getRealPath("/photo");
					String src = "/qiuzhi/photo/"+fileName;
					info.setPhoto(src);//设置头像路径
					OutputStream os = new FileOutputStream(savepath+"\\"+fileName);
					int len = 0;
					byte[] buff = new byte[1024];
					while((len=in.read(buff))!=-1){
						os.write(buff, 0, len);
					}
					os.close();
					in.close();
				}
			}
		} catch (FileUploadException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}finally{
			UserInfoService us = new UserInfoServiceImpl();
			System.out.println(" 昵称  "+info.getNickname()+" 签名  "+info.getSignature());
			int a = us.update(info);
			if(a>0){
				request.getRequestDispatcher("/ShowMainPageByUser").forward(request, response);
			}
		}
	}

}
